package service

import (
	"awesomeProject2/global"
	"awesomeProject2/model"
	"awesomeProject2/model/request"
	"awesomeProject2/model/response"
	"strconv"
)

func GetWorksDynamic(info request.WorkSearchInfo) (err error, list interface{}, total int64) {
	var res []response.WorkResponse
	var userIds []uint
	limit := info.PageSize
	offset := info.PageSize * (info.PageNum - 1)
	db := global.GVA_DB.Model(&model.Work{}).Select("teacher.teacher_name as name, work.*").
		Joins("left join teacher on work.user_id = teacher.user_id")

	if info.WorkName != "" {
		db = db.Where("work_name LIKE ?", "%"+info.WorkName+"%")
	}

	if info.PubName != "" {
		db = db.Where("pub_name LIKE ?", info.PubName)
	}

	if info.WorkCategory != "" {
		db = db.Where("work_category = ?", info.WorkCategory)
	}

	if info.WorkLevel != "" {
		db = db.Where("work_level = ?", info.WorkLevel)
	}

	if info.Year != "" {
		year, _ := strconv.Atoi(info.Year)
		db = db.Where("year = ?", year)
	}

	if info.Name != "" {
		userIds, err = model.GetUserIdsByTeacherName(info.Name)
		if len(userIds) != 0 {
			db = db.Where("teacher.user_id IN ?", userIds)
		}
	}

	err = db.Count(&total).Error
	if err != nil {
		return err, nil, 0
	}

	err = db.Limit(limit).Offset(offset).Find(&res).Error
	return err, res, total

}
